package parsing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipWriter {
	private static String deckjspath = "deckjs";
	private static String[] deckjsextensions = { "goto", "menu", "navigation",
			"status" };

	private ZipWriter() {
	}

	public static void writeZip(String filename, File htmlFile, String theme,
			String animation) {
		System.out.println(theme);
		System.out.println(animation);
		System.out.println(filename);

		try {
			FileOutputStream fos = new FileOutputStream(filename);
			ZipOutputStream zos = new ZipOutputStream(fos);

			String html = "index.html";

			addFile(html, html, zos);
			addCore(zos);
			addThemes(theme, animation, zos);
			zos.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void addThemes(String theme, String animation,
			ZipOutputStream zos) throws IOException {
		if (!theme.equals("")) {
			File fileIn = new File(deckjspath + "/themes/style/" + theme
					+ ".css");
			addFile(fileIn, "deckjs/themes/style.css", zos);
		}

		if (!animation.equals("")) {
			File fileIn = new File(deckjspath + "/themes/transition/"
					+ animation + ".css");
			addFile(fileIn, "deckjs/themes/transition.css", zos);
		}

	}

	private static void addCore(ZipOutputStream zos) throws IOException {
		addDir(deckjspath, zos);

		for (String ext : deckjsextensions) {
			addDir(deckjspath + "/extensions/" + ext, zos);
		}
	}

	private static void addDir(String dirStr, ZipOutputStream zos)
			throws IOException {
		File dir = new File(dirStr);
		File[] files = dir.listFiles();

		for (File file : files) {
			if (file.getName().endsWith(".js")
					|| file.getName().endsWith(".css")) {
				String targetPath = dirStr + "/" + file.getName();

				System.out.println(targetPath);

				addFile(file, targetPath, zos);
			}
		}
	}

	private static void addFile(File fileIn, String filenameOut,
			ZipOutputStream zos) throws IOException {
		ZipEntry ze = new ZipEntry(filenameOut);
		zos.putNextEntry(ze);

		FileInputStream fin = new FileInputStream(fileIn);

		for (int c = fin.read(); c != -1; c = fin.read()) {
			zos.write(c);
		}

		zos.closeEntry();
		fin.close();
	}

	private static void addFile(String filenameIn, String filenameOut,
			ZipOutputStream zos) throws IOException {
		File fileIn = new File(filenameIn);
		addFile(fileIn, filenameOut, zos);
	}
}
